﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Path = System.IO.Path;

namespace 重命名工具
{
    public partial class MainWindow : Window
    {
        private List<string> failList = null;
        private string log = "";
        private double logInterval = 0.1;
        private string xuanze;  // 选择.Text
        private string yuan;    // 原.Text
        private string xian;    // 现.Text
        private bool stop;      // 停止标志

        public MainWindow()
        {
            InitializeComponent();
            // 日志，定时刷新
            DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(logInterval) };
            timer.Tick += 窗体日志;
            timer.Start();
        }
        private void 窗体日志(object sender, EventArgs e) { 日志.Text = log; }

        private void 去除空文件夹(object sender, RoutedEventArgs e)
        {
            stop = false;
            xuanze = 选择.Text;

            Task t = new Task(cleanEmptyDirs);
            t.Start();
        }
        private void cleanEmptyDirs()
        {
            failList = new List<string>();
            cleanEmptyDirs(xuanze);
            if (failList.Count > 0)
            {
                FailListOutput(failList);
                log = "有失败记录\n位于“" + xuanze + "\\失败记录.txt”";
            }
            else
            {
                log = "成功";
            }
        }
        private void cleanEmptyDirs(string path)
        {
            if (stop) return;
            try { Directory.Exists(path); } catch { return; }
            if (Directory.Exists(path))
            {
                log = "正在搜索 - " + path;
                DirectoryInfo di = new DirectoryInfo(path);
                if (di.Name.Equals(".Trashes") || di.Name.Equals(".Spotlight - V100") ||
                    di.Name.Equals("$RECYCLE.BIN") || di.Name.Equals("System Volume Information"))
                {
                    return;
                }
                string[] dirs = new string[] { "" };
                try { dirs = Directory.GetDirectories(path); } catch { return; }
                foreach (string s in dirs) { cleanEmptyDirs(s); }
                try { di.Delete(); }
                catch { return; }
            }
        }

        private void 去除隐藏文件(object sender, RoutedEventArgs e)
        {
            stop = false;
            xuanze = 选择.Text;

            Task t = new Task(cleanHideUseless);
            t.Start();
        }
        private void cleanHideUseless()
        {
            failList = new List<string>();
            cleanHideUseless(xuanze);
            if (failList.Count > 0)
            {
                FailListOutput(failList);
                log = "有失败记录\n位于“" + xuanze + "\\失败记录.txt”";
            }
            else
            {
                log = "成功";
            }
        }
        private void cleanHideUseless(string path)
        {
            if (stop) return;
            try { Directory.Exists(path); } catch { return; }
            if (Directory.Exists(path))
            {
                log = "正在搜索 - " + path;
                DirectoryInfo di = new DirectoryInfo(path);
                if (di.Name.Equals(".Trashes") || di.Name.Equals(".Spotlight - V100") ||
                    di.Name.Equals("$RECYCLE.BIN") || di.Name.Equals("System Volume Information"))
                {
                    return;
                }
                string[] dirs = new string[] { "" };
                try { dirs = Directory.GetFileSystemEntries(path); } catch { return; }
                if (!(dirs == null || dirs.Length == 0))
                {
                    foreach (string s in dirs) { cleanHideUseless(s); }
                }
            }
            else if (File.Exists(path) && ((new FileInfo(path).Attributes & FileAttributes.Hidden) == FileAttributes.Hidden))
            {
                if (new FileInfo(path).Name.StartsWith("._") || new FileInfo(path).Name.StartsWith(".DS_Store")) {
                    try { File.Delete(path); log += "\n正在删除 - " + path; }
                    catch { failList.Add(path); return; }
                }
            }
        }

        private void 替换字符串(object sender, RoutedEventArgs e)
        {
            stop = false;
            xuanze = 选择.Text;
            yuan = 原.Text;
            xian = 现.Text;

            Task t = new Task(ReplaceString);
            t.Start();
        }
        private void ReplaceString()
        {
            failList = new List<string>();
            ReplaceString(xuanze);
            if (failList.Count > 0)
            {
                FailListOutput(failList);
                log = "有失败记录\n位于“" + xuanze + "\\失败记录.txt”";
            }
            else
            {
                log = "成功";
            }
        }
        private void ReplaceString(string path)
        {
            if (stop) return;
            try { Directory.Exists(path); File.Exists(path); } catch { return; }
            if (Directory.Exists(path))
            {
                string[] dirs = new string[] { "" };
                try { dirs = Directory.GetFileSystemEntries(path); }
                catch { return; }
                foreach (string s in dirs) { ReplaceString(s); }
                string parentName = new DirectoryInfo(path).Parent.FullName;
                string dirName = new DirectoryInfo(path).Name;
                log = "正在处理 - " + parentName + "\n 重命名 " + dirName + " 为 " + dirName.Replace(yuan, xian);
                try { Directory.Move(path, parentName + Path.DirectorySeparatorChar + dirName.Replace(yuan, xian)); }
                catch { return; }
            }
            if(File.Exists(path))
            {
                string dirName = new FileInfo(path).DirectoryName;
                string fileName = new FileInfo(path).Name;
                log = "正在处理 - " + dirName + "\n 重命名 " + fileName + " 为 " + fileName.Replace(yuan, xian);
                try { File.Move(path, dirName + Path.DirectorySeparatorChar + fileName.Replace(yuan, xian)); }
                catch { return; }
            }
        }

        private void 选择文件夹(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (System.Windows.Forms.DialogResult.OK == dialog.ShowDialog())
            {
                选择.Text = dialog.SelectedPath;
            }
        }

        // 输出失败记录
        private void FailListOutput(List<string> failList)
        {
            StreamWriter failTxt = File.CreateText(xuanze + "\\失败记录.txt");
            failTxt.AutoFlush = true;
            foreach (string s in failList)
            {
                failTxt.WriteLine(s);
            }
        }

        private void STOP_Click(object sender, RoutedEventArgs e)
        {
            stop = true;
        }
    }
}
